// 定义邮件数据类型接口
export interface MailMessage {
  id: number;
  sender: string;
  recipients: string[];
  subject: string;
  created_at: string;
  attachments: any[];
  formats: string[];
}

// 存储已监听的邮件ID，避免重复处理
let existingIds: number[] = [];
// 轮询定时器ID（用于后续清除）
let pollTimer: number | null = null;

/**
 * 获取所有邮件列表
 */
export const fetchMails = async (): Promise<MailMessage[]> => {
  try {
    const response = await fetch('http://localhost:1080/api/messages');
    if (!response.ok) throw new Error(`请求失败: ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error('获取邮件列表失败:', error);
    return [];
  }
};

/**
 * 获取指定ID的邮件正文
 * @param id 邮件ID
 */
export const fetchMailContent = async (id: number): Promise<string> => {
  try {
    const response = await fetch(`http://localhost:1080/api/messages/${id}/plain`);
    if (!response.ok) throw new Error(`获取正文失败: ${response.status}`);
    return await response.text();
  } catch (error) {
    console.error(`获取邮件 ${id} 正文失败:`, error);
    return '';
  }
};

/**
 * 检测新增邮件并处理
 * @param onNewMail 新增邮件的回调函数（用于通知组件）
 */
const checkForNewMails = async (onNewMail: (mail: MailMessage, content: string) => void) => {
  const currentMails = await fetchMails();
  if (currentMails.length === 0) return;

  // 筛选出新增邮件（ID不在现有列表中）
  const newMails = currentMails.filter(mail => !existingIds.includes(mail.id));
  
  for (const mail of newMails) {
    const content = await fetchMailContent(mail.id);
    onNewMail(mail, content); // 调用回调，将新邮件信息传递给组件
    existingIds.push(mail.id); // 记录已处理的ID
  }
};

/**
 * 启动轮询监听
 * @param interval 轮询间隔（毫秒，默认3000）
 * @param onNewMail 新增邮件的回调函数
 */
export const startMailPolling = (
  interval: number = 3000,
  onNewMail: (mail: MailMessage, content: string) => void
) => {
  // 先清除可能存在的旧定时器，避免重复轮询
  if (pollTimer) clearInterval(pollTimer);
  
  // 初始化：先获取一次现有邮件ID，避免首次启动时误判旧邮件为新邮件
  fetchMails().then(mails => {
    existingIds = mails.map(mail => mail.id);
    console.log('邮件监听初始化完成，开始轮询...');
  });
  
  // 启动定时轮询
  pollTimer = window.setInterval(() => {
    checkForNewMails(onNewMail);
  }, interval);
};

/**
 * 停止轮询监听
 */
export const stopMailPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
    console.log('邮件轮询已停止');
  }
};